<?php

namespace app\admin\controller\setting;

use app\admin\logic\system\SystemConfigLogic;
use app\basic\BaseController;
use exception\ApiException;
use support\utils\Cache;
use support\Request;
use support\Response;
use think\Exception;

class SmsController extends BaseController
{
    /**
     * 构造
     */
    public function __construct()
    {
        $this->logic = new SystemConfigLogic();
        parent::__construct();
    }

    /**
     * 获取配置列表
     */
    public function lists()
    {
        $sms = $this->logic->getConfig("sms")['value']['engine'];
        return $this->success($this->logic->getStrongConfig($sms),'ok');
    }

    /**
     * 编辑存储配置
     * @param Request $request
     * @return \support\Response
     */
    public function edit(Request $request)
    {
        $param = $request->post();
        // 验证参数
        if (!isset($param['status'], $param['sms_type'],$param['access_key'], $param['secret_key'])) {
                return $this->fail("缺少必要的参数");
        }
        if(empty($param['access_key']) || empty($param['secret_key'])){
             return $this->fail("部分参数为空");
        }
        if($param['sms_type'] != 'HY'){
           if (empty($param['signature']) || empty($param['template_id'])) {
                return $this->fail("部分参数为空");
            }
        }
        if (!in_array($param['status'], ["1", "2"], true)) {
            return $this->fail("状态值无效");
        }
        $storage = $this->logic->getConfig("sms")['value'];
        if($param['status'] == "1"){
            $storage['engine'] = array_map(function ($value) use ($param) {
                return [
                    'name' => $value['name'],
                    'sms_type' => $value['sms_type'],
                    'status'       => ($value['sms_type'] == $param['sms_type']) ? $param['status'] : "2",
                    'config' => isset($value['config'])?$value['config']:[],
                ];
            }, $storage['engine']);
            $storage['default'] = $param['sms_type'];
        }
        $config = [
            'access_key' => $param['access_key'],
            'secret_key' => $param['secret_key'],
            'signature' => isset($param['signature'])?$param['signature']:'',
            'template_id' => isset($param['template_id'])?$param['template_id']:''
        ];
        $storage['engine'][$param['sms_type']]['config'] = $config;
        try {
            if ($this->logic->where(['key' => 'sms'])->update(['value' => json_encode($storage, JSON_UNESCAPED_UNICODE)])) {
                // 清空缓存
                Cache::clear('config_sms');
                return $this->success("修改成功");
            } else {
                throw new ApiException("更新失败");
            }
        } catch (Exception $e) {
            return $this->fail("修改失败: " . $e->getMessage());
        }
    }


     /**
     * 修改状态
     * @param Request $request
     * @return Response
     */
    public function changeStatus(Request $request) : Response
    {
        $sms_type = $request->input('sms_type', '');
        $status = $request->input('status', 1);
        $storage = $this->logic->getConfig("sms")['value'];
        foreach ($storage['engine'] as &$engine) {
            if ($engine['sms_type'] == $sms_type) {
                $engine['status'] = $status;
            } else {
                $engine['status'] = "2";
            }
        }
        $storage['default'] = $sms_type;
        try {
            if ($this->logic->where(['key' => 'sms'])->update(['value' => json_encode($storage, JSON_UNESCAPED_UNICODE)])) {
                 // 清空缓存
                Cache::clear('config_sms');
                return $this->success("修改成功");
            } else {
                throw new ApiException("更新失败");
            }
        } catch (Exception $e) {
            return $this->fail("修改失败: " . $e->getMessage());
        }
    }

}